package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhenfeng
 * @Date 2021/5/13
 */
@Component
@Setter
@Getter
public class MySeckillProductJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {
        //每天定时清空前一天的秒杀商品
        redisTemplate.delete(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time));
        redisTemplate.delete(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time));
        //获取秒杀商品集合
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.querySeckillProductByTime(Integer.parseInt(time));
        if(result != null && !result.hasError()){
            List<SeckillProductVo> data = result.getData();
            if(data != null && data.size() > 0){
                for (SeckillProductVo vo : data) {
                    //缓存秒杀商品列表
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time), vo.getId().toString(), JSON.toJSONString(vo));
                    //缓存秒杀商品数量
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time), vo.getId().toString(), vo.getStockCount()+"");
                }
                System.out.println("数据保存了 time=" + time);
            }
        }
    }
}
